package org.example.ams.service.impl.generator;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.ams.dao.generator.ICodeGeneratorDao;
import org.example.ams.entity.generator.TableFields;
import org.example.ams.service.generator.ICodeGeneratorService;
import org.springframework.stereotype.Service;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @author cheval
 */
@Service
public class CodeGeneratorServiceImpl implements ICodeGeneratorService {

    private  ICodeGeneratorDao codeGeneratorDao;
    private final static SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;

    static {
        String strFilePath = Thread.currentThread().getContextClassLoader().getResource("generatorConfig.xml").toString();
        strFilePath = strFilePath.replace("file:/", "");
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(strFilePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }


    private ICodeGeneratorDao getMapper() {
        sqlSession = sqlSessionFactory.openSession();
        return sqlSession.getMapper(ICodeGeneratorDao.class);
    }

    private void closeSession() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Override
    public List<String> queryAllTables() {
        codeGeneratorDao = getMapper();
        List<String> tables1 = codeGeneratorDao.selectAllTables();
        closeSession();
        return tables1;
    }

    @Override
    public List<TableFields> queryTableFields(String tableName) {
        if (tableName == null || "".equals(tableName.trim())) {
            return null;
        }
        codeGeneratorDao = getMapper();
        List<TableFields> tableFields = codeGeneratorDao.selectTableFields(tableName);
        closeSession();
        return tableFields;
    }


}
